<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="活动名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select v-model="listQuery.type" placeholder="活动类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.status" placeholder="活动状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus" @click="handleCreate">
        添加活动
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="活动名称" prop="name" min-width="150" />
      <el-table-column label="活动类型" width="120" align="center">
        <template slot-scope="{row}">
          <el-tag>{{ row.typeText }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="优惠规则" min-width="200">
        <template slot-scope="{row}">
          <div v-if="row.type === 1">满{{ row.minAmount }}减{{ row.discount }}</div>
          <div v-else-if="row.type === 2">打{{ row.discount }}折</div>
          <div v-else>{{ row.ruleDesc }}</div>
        </template>
      </el-table-column>
      <el-table-column label="活动时间" width="300" align="center">
        <template slot-scope="{row}">
          <span>{{ row.startTime }} 至 {{ row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.statusText }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status === 0" type="success" size="mini" @click="handleModifyStatus(row, 1)">
            开启
          </el-button>
          <el-button v-else type="warning" size="mini" @click="handleModifyStatus(row, 0)">
            关闭
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 活动编辑弹窗 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="活动类型" prop="type">
          <el-select v-model="temp.type" class="filter-item" @change="handleTypeChange">
            <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- 满减规则 -->
        <template v-if="temp.type === 1">
          <el-form-item label="满减金额" prop="minAmount">
            <el-input-number v-model="temp.minAmount" :min="0" :precision="2" />
          </el-form-item>
          <el-form-item label="优惠金额" prop="discount">
            <el-input-number v-model="temp.discount" :min="0" :precision="2" />
          </el-form-item>
        </template>
        <!-- 折扣规则 -->
        <template v-if="temp.type === 2">
          <el-form-item label="折扣率" prop="discount">
            <el-input-number v-model="temp.discount" :min="0" :max="10" :precision="1" />
            <span class="discount-tip">折</span>
          </el-form-item>
        </template>
        <el-form-item label="活动时间" prop="timeRange">
          <el-date-picker
            v-model="temp.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="活动说明">
          <el-input v-model="temp.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getActivityList, createActivity, updateActivity, deleteActivity } from '@/api/promotion'
import { Pagination } from 'element-ui'

export default {
  name: 'PromotionActivity',
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'info',
        1: 'success',
        2: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: undefined,
        type: undefined,
        status: undefined
      },
      typeOptions: [
        { label: '满减活动', value: 1 },
        { label: '折扣活动', value: 2 },
        { label: '特价活动', value: 3 }
      ],
      statusOptions: [
        { label: '未开始', value: 0 },
        { label: '进行中', value: 1 },
        { label: '已结束', value: 2 }
      ],
      temp: {
        id: undefined,
        name: '',
        type: 1,
        minAmount: 0,
        discount: 0,
        timeRange: [],
        description: '',
        status: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑活动',
        create: '创建活动'
      },
      rules: {
        name: [{ required: true, message: '活动名称必填', trigger: 'blur' }],
        type: [{ required: true, message: '请选择活动类型', trigger: 'change' }],
        timeRange: [{ required: true, message: '请选择活动时间', trigger: 'change' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getActivityList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        type: 1,
        minAmount: 0,
        discount: 0,
        timeRange: [],
        description: '',
        status: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.temp)
          data.startTime = data.timeRange[0]
          data.endTime = data.timeRange[1]
          createActivity(data).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.temp.timeRange = [this.temp.startTime, this.temp.endTime]
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const data = Object.assign({}, this.temp)
          data.startTime = data.timeRange[0]
          data.endTime = data.timeRange[1]
          updateActivity(data).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该活动?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteActivity(row.id).then(() => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      })
    },
    handleModifyStatus(row, status) {
      const text = status === 1 ? '开启' : '关闭'
      this.$confirm(`确认${text}该活动?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateActivity({
          id: row.id,
          status: status
        }).then(() => {
          this.$notify({
            title: '成功',
            message: `${text}成功`,
            type: 'success',
            duration: 2000
          })
          row.status = status
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.discount-tip {
  margin-left: 10px;
  color: #606266;
}
</style> 